package com.tanglongan.concurrent.thread;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.LockSupport;

public class StatusDemo {

    public static final long MAX_TURN = 5;
    static int threadSeqNumber = 0;
    static List<Thread> threadList = new ArrayList<>();

    private static void printThreadStatus() {
        for (Thread thread : threadList) {
            System.out.println(thread.getName() + " 状态为 " + thread.getState());
        }
    }

    private static void addStatusThread(Thread thread) {
        threadList.add(thread);
    }

    private static void sleepMilliSeconds(int l) {
        LockSupport.parkNanos(l * 1000L * 1000L);
    }

    static class StatusDemoThread extends Thread {
        public StatusDemoThread() {
            super("statusPrintThread " + (++threadSeqNumber));
            addStatusThread(this);
        }

        @Override
        public void run() {
            System.out.println(getName() + "=====>状态为 " + getState());
            for (int i = 0; i < MAX_TURN; i++) {
                sleepMilliSeconds(500);
                printThreadStatus();
            }
            System.out.println(getName() + "- 运行结束. ");
        }
    }


    public static void main(String[] args) {
        addStatusThread(Thread.currentThread());
        Thread sThread1 = new StatusDemoThread();
        System.out.println(sThread1.getName() + "- 状态为 " + sThread1.getState());
        Thread sThread2 = new StatusDemoThread();
        System.out.println(sThread2.getName() + "- 状态为 " + sThread2.getState());
        Thread sThread3 = new StatusDemoThread();
        System.out.println(sThread3.getName() + "- 状态为 " + sThread3.getState());


        sThread1.start();
        sleepMilliSeconds(500);
        sThread2.start();
        sleepMilliSeconds(500);
        sThread3.start();
        sleepMilliSeconds(100);
    }
}
